import { definePageConfig, useRequest } from 'ice';
import userService, { userType } from '@/services/user';
import { useMemo, useState } from 'react';
import { ColumnProps } from '@alifd/next/types/table';
import {
  Button,
  Message,
  Select,
  Table,
} from '@alifd/next';
import { PagingInfo } from '@/services/images';

import OperationMenu from '@/components/operationMenu';
import ManipulationMenu, { FormItemType } from '@/components/manipulationMenu';
import ZPagination from '@/components/ZPagination';
import DrawerUser from './components/DrawerUser';

export const pageConfig = definePageConfig(() => {
  return {
    title: '用户管理',
    auth: ['admin'],
  };
});

// 用户管理
export default function UserManagement() {
  // 抽屉数据
  const [drawerData, setDrawerData] = useState<any>({
    // 显示 隐藏
    isShow: false,
    // 0添加 1修改
    type: 0,
  });

  // 页码
  const [pagingInfo, setPagingInfo] = useState<PagingInfo>({
    take: 20,
    skip: 1,
  });
  const [formValue, setFormValue] = useState<userType>();
  // 获取用户列表
  const userListRequest = useRequest(userService.userList);
  // 重置
  const ResetData = () => {
    setFormValue(undefined);
    setPagingInfo({
      take: 20,
      skip: 1,
    });
  };
  // 表格数据
  const ColumnItem: Array<ColumnProps & FormItemType> = useMemo(() => {
    const del = (record: any) => {
      userService.deleteUser(record.id).then((data) => {
        if (data.success) {
          Message.success(`${record.name}删除成功`);
          ResetData();
        }
      });
    };
    return [
      {
        title: '编号',
        dataIndex: 'id',
        width: 60,
        align: 'center',
      },
      {
        title: '身份',
        dataIndex: 'status',
        width: 60,
        align: 'center',
        isSelect: true,
        cell: value => value.name,
        customInput: (<Select
          className="w-full"
          hasClear
        >
          <Select.Option value={0}>管理员</Select.Option>
          <Select.Option value={1}>用户</Select.Option>
        </Select>),
      },
      {
        title: '用户名',
        dataIndex: 'name',
        align: 'center',
        placeholder: '请输入用户名',
        isSelect: true,
      },
      {
        title: '邮箱',
        dataIndex: 'email',
        align: 'center',
        placeholder: '请输入邮箱',
        isSelect: true,
      },
      {
        title: '注册时间',
        dataIndex: 'createdAt',
        width: 150,
        align: 'center',
        cell: value => new Date(value).toLocaleString(),
      },
      {
        lock: 'right',
        width: 90,
        align: 'center',
        cell: (_value, _index, record) => (<OperationMenu data={[
          {
            click: () => setDrawerData({
              isShow: true,
              type: 1,
              record: record,
            }),
            children: <Button text type="primary">修改</Button>,
          },
          {
            click: () => del(record),
            children: <Button text style={{ color: 'red' }}>删除</Button>,
          },
        ]}
        />),
      },
    ];
  }, []);


  // 表格数据
  const dataSource = useMemo(() => {
    let dataSource: userType[] = [];
    if (userListRequest.data && userListRequest.data.data) {
      dataSource = userListRequest.data.data.results;
    }
    return dataSource;
  }, [userListRequest]);
  // 筛选
  const handleSubmit = (values: any, errors: any) => {
    if (!errors) {
      if (values.name == '') values.name = undefined;
      if (values.email == '') values.email = undefined;
      values.status = { id: values.status };
      setFormValue(values);
      userListRequest.run({
        ...pagingInfo,
        skip: 1,
      }, values);
    }
  };
  return (<div className="h-full flex flex-col">
    {/* 表头 */}
    <ManipulationMenu
      title="用户管理"
      ColumnItem={ColumnItem}
      onSubmitClick={handleSubmit}
      onResetClick={ResetData}
      customBtn={<Button
        type="primary"
        onClick={() => setDrawerData({
          isShow: true,
          type: 0,
        })}
      >
        添加
      </Button>}
    />

    <div>
      {/* 表格 */}
      <Table.StickyLock
        style={{ background: 'white' }}
        loading={userListRequest.loading}
        dataSource={dataSource}
        fixedHeader
        maxBodyHeight={'calc(100vh - 380px)'}
      >
        {ColumnItem.map((item) => {
          return (<Table.Column {...item} />);
        })}
      </Table.StickyLock>
      {/* 页码 */}
      <ZPagination
        pagingInfo={pagingInfo}
        setPagingInfo={setPagingInfo}
        total={userListRequest.data?.data?.total}
        onChange={(pagingInfo) => userListRequest.run(pagingInfo, formValue)}
      />
    </div>
    {/* 修改用户弹窗 */}
    <DrawerUser
      type={drawerData.type}
      isShow={drawerData.isShow}
      onClose={() => setDrawerData({
        ...drawerData,
        isShow: false,
      })}
      record={drawerData.record}
      onUpdate={ResetData}
    />
  </div>);
}
